/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.boxin.ims.modules.wechat.entity.Option;
import com.boxin.ims.modules.wechat.entity.Question;
import com.boxin.ims.modules.wechat.entity.Questionnaire;
import com.boxin.ims.modules.wechat.service.OptionService;
import com.boxin.ims.modules.wechat.service.QuestionService;
import com.boxin.ims.modules.wechat.service.QuestionnaireService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.utils.WechatUtils;

/**
 * 调查问卷问题Controller
 * @author XiaoQian
 * @version 2014-05-09
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/wechat/question")
public class QuestionController extends BaseController {

	@Autowired
	private QuestionService questionService;
	
	@Autowired
	private QuestionnaireService questionnaireService;
	
	@Autowired
	private WechatDaoHelper wechatDaoHelper;

	
	@Autowired
	private OptionService optionService;
	
	@ModelAttribute
	public Question get(@RequestParam(required=false) Long id) {
		if (id != null){
			return questionService.get(id);
		}else{
			return new Question();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(Question question, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			question.setUser(user);
		}
		String questionnaireId=request.getParameter("questionnaireId");
		Questionnaire questionnaire = null;
		if(questionnaireId!=null){
			questionnaire=questionnaireService.get(Long.parseLong(questionnaireId));
			question.setQuestionnaire(questionnaire);
		}
		
        Page<Question> page = questionService.find(new Page<Question>(request, response), question); 
        model.addAttribute("page", page);
		return "modules/wechat/questionList";
	}
	
	
	@RequestMapping(value = "voterResult")
	public String voterResult(HttpServletRequest request, HttpServletResponse response, Model model) {
		String questionnaireId=request.getParameter("questionnaireId");
		List<Question> questionList=null;
		Questionnaire questionnaire = null;
		if(questionnaireId!=null){
			questionnaire=questionnaireService.get(Long.parseLong(questionnaireId));
			questionList= questionService.findVoterByQuestionnaireId(Long.parseLong(questionnaireId)); 
		}
		Integer number=0;
		for (Question question : questionList) {
			if(question.getNumber()==null){
				question.setNumber(0);
			}
			number+=question.getNumber();
		}
		
		model.addAttribute("number", number);
		model.addAttribute("questionnaire", questionnaire);
        model.addAttribute("questionList", questionList);
		return "modules/wechat/voterResultList";
	}
	
	@RequestMapping(value = "voterList")
	public String voterList(Question question, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			question.setUser(user);
		}
		String questionnaireId=request.getParameter("questionnaireId");
		Questionnaire questionnaire = null;
		if(questionnaireId!=null){
			questionnaire=questionnaireService.get(Long.parseLong(questionnaireId));
			question.setQuestionnaire(questionnaire);
		}
		
        Page<Question> page = questionService.find(new Page<Question>(request, response), question); 
        model.addAttribute("page", page);
		return "modules/wechat/voterList";
	}

	@RequestMapping(value = "form")
	public String form(Question question, Model model, HttpServletRequest request) {
		
		String questionnaireId=request.getParameter("questionnaireId");
		Questionnaire questionnaire = null;
		if(questionnaireId!=null){
			questionnaire=questionnaireService.get(Long.parseLong(questionnaireId));
			question.setQuestionnaire(questionnaire);
		}
		
		User user = UserUtils.getUser();
		if (question.getUser() == null || question.getUser().getId() <1){
			question.setUser(user);
		}
		
		model.addAttribute("questionnaireId", questionnaireId);
		model.addAttribute("question", question);
		if(questionnaire!=null&&questionnaire.getType()!=null){
			if(questionnaire.getType().equals("2")){
				return "modules/wechat/voterForm";
			}
		}
		return "modules/wechat/questionForm";
	}

	@RequestMapping(value = "save")
	public String save(Question question, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		if (!beanValidator(model, question)){
			return form(question, model, request);
		}
		questionService.save(question);
		
		String[] str= request.getParameterValues("options");
		
		
		Map<String , Object> params =new HashMap<String, Object>();
		params.put("question_id", question.getId());
		wechatDaoHelper.deleteOptionByquestionId(params);
		
		
		if(str!=null){
			for (int i = 0; i < str.length; i++) {
				if(!str[i].equals("")){
					
					Option option=new Option();
					option.setName(str[i]);
					option.setQuestion(question);
					optionService.save(option);
				}
			}
		}
		
		addMessage(redirectAttributes, "保存调查问卷问题成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/question/form?questionnaireId="+question.getQuestionnaire().getId();
	}
	
	@RequestMapping(value = "saveVoter")
	public String saveVoter(@RequestParam("picFile1") MultipartFile picFile1,Question question, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		if (!beanValidator(model, question)){
			return form(question, model, request);
		}
		
		if(picFile1 != null && picFile1.getOriginalFilename().length()>4){
			String picFilePath = WechatUtils.getWechatQuestionnaireSavePath(request)+File.separator;
			FileUtils.createDirectory(picFilePath);
			String sname = picFile1.getOriginalFilename();
			String fileType = sname.substring(sname.lastIndexOf("."));
			String fname  = UserUtils.getUser().getLoginName()+	"_voter_"+System.currentTimeMillis()+fileType;
			File file = new File(picFilePath+fname);
			System.out.println("保存文件:"+picFilePath+fname);
			try {
				picFile1.transferTo(file);
				question.setShowPic(file.getName());
			} catch (Exception e) {
				System.out.println("上传文件失败:"+picFilePath+fname);
				e.printStackTrace();
			}
			
		}
		question.setNumber(0);
		questionService.save(question);
		
		
		addMessage(redirectAttributes, "保存成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/question/form?questionnaireId="+question.getQuestionnaire().getId();
	}
	
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		questionService.delete(id);
		
		Question question=questionService.get(id);
		
		Iterator<Option> it=question.getOption().iterator();
		
		while (it.hasNext()) {
			Option option = it.next();
			optionService.delete(option.getId());
		}
		
		addMessage(redirectAttributes, "删除调查问卷问题成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/question/?repage";
	}

}
